namespace Pp.Core.FluentNH.Listeners
{
    using System;
    using Domain.Model;
    using NHibernate.Event;
    using NHibernate.Persister.Entity;

    public class CreateUpdateListener : IPreUpdateEventListener, IPreInsertEventListener
    {
        public bool OnPreUpdate(PreUpdateEvent @event)
        {
            var entity = @event.Entity as IEntity;

            if (entity != null)
            {
                var now = DateTime.UtcNow;
                Set(@event.Persister, @event.State, "ModifyDate", now);

                entity.ModifyDate = now;
            }

            return false; // Do not veto the operation
        }

        public bool OnPreInsert(PreInsertEvent @event)
        {
            var entity = @event.Entity as IEntity;

            if (entity != null)
            {
                var now = DateTime.UtcNow;
                Set(@event.Persister, @event.State, "CreateDate", now);
                entity.CreateDate = now;
            }

            return false; // Do not veto the operation
        }

        private static void Set(IEntityPersister persister, object[] state, string propertyName, object value)
        {
            var index = Array.IndexOf(persister.PropertyNames, propertyName);

            if (index == -1)
                return;
            state[index] = value;
        }
    }
}